package server

import (
	"awesomeTask/application/client"
	awesomeTask "awesomeTask/application/task"
	"awesomeTask/application/variable"
	awesomeTask2 "awesomeTask/commom"
	"awesomeTask/system/echo"
	event2 "awesomeTask/system/event"
	"awesomeTask/system/helper"
	"awesomeTask/system/kernel"
	"awesomeTask/system/log"
	"awesomeTask/system/safe"
	TcpServer "awesomeTask/system/tcpServer/tcpServer"
	_ "container/list"
	"fmt"
	"net"
	"strconv"
)

//var connections map[string]interface{} = map[string]interface{}{}
/*
发送数据给其他节点
*/
func SendClient(conn *net.TCPConn, message string) {
	_, _ = conn.Write([]byte(message))
}

/**
派遣任务给到指定的节点运行
*/
func SendTask(conn *net.TCPConn, taskId int) {
	SendClient(conn, strconv.Itoa(taskId))
}

/**
断开与每个节点的链接
*/
func closeClient(waitList map[string]interface{}, ipAddress string) map[string]interface{} {
	info := waitList[ipAddress].(map[string]interface{})
	connection := info["connnection"].(*net.TCPConn)
	_ = connection.Close()
	delete(info, ipAddress)
	return info
}
func RunAsServer(port int) {
	tcpServer := TcpServer.TcpServer{}
	BindEvent()
	tcpServer.OnStart(func() {
		go awesomeTask.Scan()
		log.GetLogger().Info("监听开始,监听端口:" + strconv.Itoa(port))
		BindEvent()
	})
	tcpServer.OnConnect(func(connection net.Conn) {
		fmt.Println("接受到来" + connection.RemoteAddr().String() + "的连接")
		connect := make(map[string]interface{})
		connect["connect"] = connection
		safe.Lock()
		client.Nodes[connection.RemoteAddr().String()] = client.InitNode(connection.RemoteAddr().String(), connection)
		safe.Unlock()
	})
	tcpServer.OnMessage(func(conn net.Conn, clientMsg string) {
		ioc := kernel.GetIocInstance()
		if awesomeTask2.SafeCheck(clientMsg) == false {
			conn.Close()
			log.GetLogger().Warn("非法连接:无效clientToken")
			return
		}
		m := helper.JsonDecode(clientMsg).(map[string]interface{})
		m["connection"] = conn
		m["ipAddress"] = conn.RemoteAddr().String()
		eventName := m["event"].(string)
		helper.PrintJson(m)
		if _, ok := variable.EventServerMap[eventName]; ok {
			echo.Green("客戶端 已经注册事件回调不在使用Handler:" + eventName)
			event2.Dispatch(eventName, m)
			return
		}
		handler := ioc.GetInstanceOrCreate(variable.ServerEventHandlerInstance)
		if ioc.MethodExist(handler, m["event"].(string)) {
			ioc.CallFunByName(handler, m["event"].(string), m)
			return
		} else {
			if event2.HasTmpEvent(eventName) {
				echo.Green("事件调用:" + eventName)
				event2.Dispatch(eventName, m)
				return
			}
		}
		log.GetLogger().Error("无法解析的事件:" + eventName)
	})
	tcpServer.OnClose(func(conn net.Conn) {
		if client.ServerCon != nil && conn.RemoteAddr().String() == client.ServerCon.RemoteAddr().String() {
			client.ServerCon = nil
		}
		event2.Dispatch(variable.ON_WS_NOTICE_DISCONNECTION, client.Nodes[conn.RemoteAddr().String()].UniqueId)
		delete(client.Nodes, conn.RemoteAddr().String())
		log.GetLogger().Error("节点断开连接:" + conn.RemoteAddr().String())

	})
	tcpServer.Start(port, false)
}
